package service

import (
	"day12_12_homework/config"
	"day12_12_homework/internal/models/dao"
	"day12_12_homework/pkg"
	"strconv"
	"time"
)

func UserRegister(tel, password string) (uint, string) {
	user := dao.User{
		Tel:      tel,
		UserName: tel,
		Password: pkg.Md5Hash(password + "1234"),
		Status:   1,
	}
	err := config.DB.Model(&dao.User{}).Create(&user).Error
	if err != nil {
		return 0, "注册失败"
	}
	return user.ID, ""
}

func UserLogin(tel, password string) (string, string) {
	var user *dao.User
	err := config.DB.Model(&dao.User{}).Where("tel=?", tel).Limit(1).Find(&user).Error
	if err != nil {
		return "", "登录失败"
	}
	if user.ID == 0 {
		return "", "登录失败,用户不存在"
	}
	if user.Password != pkg.Md5Hash(password+"1234") {
		return "", "登录失败"
	}

	handler, _ := config.JwtToken.TokenHandler(strconv.Itoa(int(user.ID)))

	config.Rdb.Set(config.Ctx, "User_Token_"+strconv.Itoa(int(user.ID)), handler, time.Minute*time.Duration(config.Configs.JWT.Times))

	return handler, ""
}

func UserDel(id int) string {
	err := config.DB.Model(&dao.User{}).Where("id=?", id).Delete(&dao.User{}).Error
	if err != nil {
		return "注销失败"
	}
	return ""
}

func RealName(id int, name string, idCard string) (int, string) {
	if pkg.Real(name, idCard) {
		reals := dao.RealName{
			UserId:    id,
			RealNames: name,
			IdCard:    idCard,
		}
		err := config.DB.Model(&dao.RealName{}).Create(&reals).Error
		if err != nil {
			return 0, "实名失败"
		}
		return int(reals.ID), ""
	}

	return 0, "实名失败"
}

func CreateMessages(id int) {
	address := &dao.Address{
		UserId: id,
	}
	config.DB.Model(&dao.Address{}).Create(&address)
	messages := dao.UserMessage{
		UserId:    id,
		AddressId: int(address.ID),
	}
	config.DB.Model(&dao.UserMessage{}).Create(&messages)
}
